package com.beone.smart.smartBeauty.config;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

/**
 * @author :yangjie
 * desc :
 * @date :2020/3/30
 **/
@Aspect
@Component
@Slf4j
public class WebLogAspect {
    /**
     * 切入点描述
     */
    @Pointcut("execution(public * com.beone.smart.smartBeauty.controller..*.*(..))")
    public void uiControllerLog() {
    }

    /**
     * 1）execution(public * *(..))——表示匹配所有public方法
     * 2）execution(* set*(..))——表示所有以“set”开头的方法
     * 3）execution(* com.xyz.service.AccountService.*(..))——表示匹配所有AccountService接口的方法
     * 4）execution(* com.xyz.service.*.*(..))——表示匹配service包下所有的方法
     * 5）execution(* com.xyz.service..*.*(..))——表示匹配service包和它的子包下的方法
     *
     * @param joinPoint point
     */
    @Around("uiControllerLog()") //在切入点的方法run之前要干的
    public Object logBeforeController(ProceedingJoinPoint joinPoint) throws Throwable {
        /**
         * 这个RequestContextHolder是Springmvc提供来获得请求的东西
         */
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        assert requestAttributes != null;
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        // 记录下请求内容
        log.info("请求url为{}", request.getRequestURL().toString());
        log.info("HTTP_METHOD:{}", request.getMethod());
        log.info("IP:{}", request.getRemoteAddr());
        log.info("THE ARGS OF THE CONTROLLER :{}", Arrays.toString(joinPoint.getArgs()));
        //下面这个getSignature().getDeclaringTypeName()是获取包+类名的   然后后面的joinPoint.getSignature.getName()获取了方法名
        log.info("CLASS_METHOD : {}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());
        //logger.info("################TARGET: " + joinPoint.getTarget());//返回的是需要加强的目标类的对象
        //logger.info("################THIS: " + joinPoint.getThis());//返回的是经过加强后的代理类的对象
        Object result = joinPoint.proceed(joinPoint.getArgs());
        log.info("响应结果为{}", JSON.toJSONString(result));
        return result;
    }
}
